const jwt = require('jsonwebtoken')
const errorTypes = require('../contants/error-types')
const {PUBLIC_KEY} = require('../app/config')
const authService = require('../service/auth.service')

// 验证用户是否登录
const verifyAuth = async (ctx, next) => {
  // 获取token, 验证token
  const authorization = ctx.request.header.authorization;
  
  if(!authorization) {
    const error = new Error(errorTypes.UNAUTHORIZATION)
    return ctx.app.emit('error', error, ctx)
  }
  const token = authorization.replace('Bearer ', '')

  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256']
    })
    ctx.user = result
    await next()
  } catch (err) {
    console.log(err.message)
    const error = new Error(errorTypes.UNAUTHORIZATION)
    return ctx.app.emit('error', error, ctx)
  }
}

// 验证用户是否具有权限，其实就是判断该资源是否属于该用户
const verifyPermission = async (ctx, next) => {
  /**
   * 这里我们操作数据库的函数需要传入表名，
   * 获取表名就是通过ctx.params 来获取:momentId, 然后通过replace把Id删除就是需要的表名
  */
  const [resourceKey] = Object.keys(ctx.params)
  const tableName = resourceKey.replace('Id', '')
  const resourceId = ctx.params[resourceKey]
  const userId = ctx.user.id

  try {
    const isPermission = await authService.checkResource(tableName, resourceId, userId)
    if(!isPermission) throw new Error()
    await next()
  } catch (error) {
    console.log(error.message)
    return
  }
}

module.exports = {
  verifyAuth,
  verifyPermission
}